package com.btpj.module_login.ui

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.btpj.jetpack.base.BaseViewModel
import com.btpj.jetpack.entity.User
import com.btpj.jetpack.utils.ToastUtil
import com.btpj.jetpack.entity.ApiResult
import com.btpj.module_login.data.remote.LoginRepository
import kotlinx.coroutines.launch

class LoginViewModel(private val repository: LoginRepository) : BaseViewModel() {

    val loginLiveData = MutableLiveData<User>()

    override fun start() {}

    fun login(username: String, password: String) {
        viewModelScope.launch {
            when (val result = repository.login(username, password)) {
                is ApiResult.Success -> loginLiveData.postValue(result.data)
                is ApiResult.Error -> ToastUtil.showShort(result.exception.errorMsg ?: "登录失败")
            }
        }
    }

    fun register(username: String, password: String, surePassword: String) {
        viewModelScope.launch {
            when (val result = repository.register(username, password, surePassword)) {
                is ApiResult.Success -> loginLiveData.postValue(result.data)
                is ApiResult.Error -> ToastUtil.showShort(result.exception.errorMsg ?: "注册失败")
            }
        }
    }
}